<?php
//微信服务层

namespace app\admin\service;

use app\common\Common;
use app\model\Applet;
use think\facade\Db;

class WechatService
{
    private $appletInfo;

    public function __construct($appId = 'wx9e795df72358378b')
    {
        $applet = Applet::field('id,app_id,app_secret')->where(['app_id' => $appId, 'type' => 1])->find();
        $this->appletInfo = $applet ? $applet->toArray() : [];
    }

    //返回access_token
    private function getAccessToken(): string
    {
        if (empty($this->appletInfo)) return '';

        $accessToken = Common::getWechatAppletAccessToken(
            $this->appletInfo['app_id'],
            $this->appletInfo['app_secret'],
            $this->appletInfo['id']
        );

        return !empty($accessToken) ?  $accessToken : '';
    }

    //短剧授权
    public function shortPlayAuthorize($drama_id, array $appIds)
    {
        $accessToken = $this->getAccessToken();
        if (empty($accessToken)) return false;

        $url = 'https://api.weixin.qq.com/wxa/sec/vod/authorizedrama?access_token='.$accessToken;
        $header = [
            'Content-Type:application/json'
        ];
        $common = [
            'drama_id' => [(int)$drama_id],
            'authz_expire_time' => 0
        ];

        $success = [];
        foreach ($appIds as $appId) {
            $result = Common::curlRequest($url, 'POST', json_encode(array_merge($common,[
                'authorized_appid' => $appId
            ]), JSON_UNESCAPED_UNICODE), $header);

            $data = json_decode($result, true);
            //flog(['result' => $data],'wechat_authorize');
            if ($data && $data['errcode'] == 0) {
                $dramaErrCode = $data['result'][0]['errcode'] ?? 1;
                if ($dramaErrCode == 0) {
                    $success[] = $appId;
                }
            }
        }
        return $success;
    }

    //剧目授权查询
    public function queryAuthorize($drama_id, $ext = []): array
    {
        $accessToken = $this->getAccessToken();
        if (empty($accessToken)) return [];

        $url = 'https://api.weixin.qq.com/wxa/sec/vod/getauthorizeobjects?access_token='.$accessToken;
        $header = [
            'Content-Type:application/json'
        ];

        $body = [
            'drama_id' => (int)$drama_id,
            'limit' => !empty($ext['limit']) ? (int)$ext['limit'] : 100,
            'offset' => !empty($ext['page']) ? (int)($ext['page'] - 1) : 0,
        ];

        if (!empty($ext['app_id'])) {
            $body['authorized_appid'] = $ext['app_id'];
        }

        $result = Common::curlRequest($url, 'POST', json_encode($body, JSON_UNESCAPED_UNICODE), $header);
        $data = json_decode($result, true);

        //flog(['result' => $data],'wechat_authorize_query');
        if ($data && $data['errcode'] == 0) {
            return [$data['objects'] ?? [], $data['total_count'] ?? 0];
        }

        return [];
    }

    //小程序公众号绑定
    public function accountBind($app_id, $bind_appid): string
    {
        $accessToken = $this->getAccessToken();
        if (empty($accessToken)) return 'access_token为空';

        $url = 'https://api.weixin.qq.com/wxadrama/bindaccount?access_token='.$accessToken;
        $header = [
            'Content-Type:application/json'
        ];
        $body = [
            'app_id' => $app_id,    //小程序app_id
            'bind_type' => 1,   //类型，1绑定，2解绑
            'bind_appid' => $bind_appid    //绑定的公众号app_id
        ];

        $result = Common::curlRequest($url, 'POST', json_encode($body, JSON_UNESCAPED_UNICODE), $header);
        $data = json_decode($result, true);

        flog(['result' => $data],'wechat_account_bind');
        if ($data && $data['errcode'] == 0) {
            return '';
        }

        return $data['errmsg'] ?? '操作失败';
    }
}